// pages/citylist/citylist.js
const app = getApp();
const cityMap = require("../../libs/map")
let QQMapWX = require('../../libs/qqmap-wx-jssdk.min');
let qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cityList: cityMap,
    location: "A",
    cityname: "定位中.."
  },
  tapLetter(event) {
    let that = this;
    that.setData({
      location: event.currentTarget.dataset.letter
    })
  },
  tapCityItem(e) {
    app.globalData.cityName = e.currentTarget.dataset.cityfullname;
    wx.navigateBack();
  },
    // 点击定位城市
    chooseLocation() {
      let that = this;
      let cname=that.data.cityname;
      if (cname == "定位失败！点击重试") {
        that.setData({
          cityname:"定位中..."
        })
        that.loadCity();
      }
    },
    //定位城市实现
    loadCity() {
      let that = this;
      //逆地址解析（坐标位置描述，坐标转地址）
      app.globalData.qqmapsdk.reverseGeocoder({
         //成功后的回调
        success: (res) => {
          // 拿到地址逆解析的城市名
          let cName = res.result.address_component.city;
          //定位成功后更新全局cityName
          app.globalData.cityName = cName;
          //模拟定位时差
          setTimeout(() => {
            that.setData({
              cityname: cName
            });
          }, 1000)
  
        },
        //失败后的回调
        fail: (err) => { 
          console.error(err);
          console.error("没有位置权限");
          // 如果当前没有位置权限
          if (err.status == 1000) { //1000代表为授权
            // 则弹出对话框，让用户去设置页面，赋予权限
            wx.showModal({
              cancelColor: "red",
              title: "提示",
              content: "是否跳转到设置页开放位置权限？",
              success: (res) => {
                if (res.confirm) {
                  // 跳转到设置页进行授权设置
                  wx.openSetting().then(openSettingRes => {
                    // 判断是否开启位置权限
                    if(openSettingRes.authSetting['scope.userLocation']){
                      that.setData({
                        cityname:"定位中..."
                      })
                      that.loadCity();
                    }
                  })
                } else {
                  console.log("NO");
                }
              }
            })
          }
          that.setData({
            cityname: "定位失败！点击重试"
          });
        },
        complete: (res) => { //完成后执行
          console.log("自动定位结束");
        }
      })
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    // that.setData({
    //   cityname: app.globalData.cityName
    // })
    that.loadCity();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})